package input;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import util.Loteria;

public class HtmToCSV {

	public void convert(File htmFile, File resultFile, Loteria loteria) {
		try {
			int bolls = 0;
			switch (loteria) {
			case MEGASENA:
				bolls = 6;
				break;
			case LOTOMANIA:
				bolls = 20;
				break;
			case LOTOFACIL:
				bolls = 15;
				break;
			}
			BufferedReader reader = new BufferedReader(new FileReader(htmFile));
			String line = null;
			do {
				line = reader.readLine();
				if (line.matches("</tr>")) {
					break;
				}
			} while (line != null);
			int cont = 0;
			BufferedWriter writer = new BufferedWriter(new FileWriter(
					resultFile));
			while ((line = reader.readLine()) != null) {
				if (line.contains("table")) {
					break;
				}
				if (line.matches("<td.*?>")) {
					if (cont == 0) {
						cont++;
						writer.append(line.substring(4, line.indexOf("</td>")));
					} else if (cont == 1) {
						cont++;
					} else if (cont > 1 && cont < bolls+2) {
						writer.append(",");
						cont++;
						writer.append(line.substring(4, line.indexOf("</td>")));
					}
				}
				if (line.matches("</tr>")) {
					cont = 0;
					writer.append("\n");
					writer.flush();
				}
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
